package com.usefullc.system.service.file.impl;

import com.usefullc.common.exception.BizException;
import com.usefullc.system.service.AbstractService;
import com.usefullc.system.service.file.FileResService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * 本地服务器上传实现类
 * @author: Sampson
 * @date: 2022-04-26 10:27
 */
@Service("localFileUploadService")
public class LocalFileResServiceImpl extends AbstractService implements FileResService {

    @Value("${usefullc.uploadPath}")
    private String uploadPath;

    @Override
    public String upload(byte [] bytes,String originalFilename,String type) {
        String fileName = UUID.randomUUID().toString()+"." +FilenameUtils.getExtension(originalFilename);
        String filePath = uploadPath + File.separator + type + File.separator +DateFormatUtils.format(new Date(),"yyyyMMdd") +File.separator + fileName;
        try {
            FileUtils.writeByteArrayToFile(new File(filePath),bytes);
            return StringUtils.removeStart(filePath,uploadPath);
        } catch (IOException e) {
            throw new BizException("upload file failed",e);
        }
    }

    @Override
    public void download(String filePath, HttpServletResponse response) {
        try{
            File file = new File(uploadPath+filePath);
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
            IOUtils.copy(new FileInputStream(file),response.getOutputStream());
        }catch (Exception e){
            throw new BizException("download file failed",e);
        }
    }
}
